from PIL import Image, ImageEnhance
import os

def adjust_brightness(input_path, output_path, brightness_factor):
    """
    Adjust the brightness of an image and save it to the output path.
    """
    with Image.open(input_path) as image:
        enhancer = ImageEnhance.Brightness(image)
        enhanced_im = enhancer.enhance(brightness_factor)
        enhanced_im.save(output_path)

def calculate_brightness(image):
    """
    Calculate the brightness of an image.
    """
    greyscale_image = image.convert('L')
    histogram = greyscale_image.histogram()
    brightness = sum(i * w for i, w in enumerate(histogram)) / sum(histogram)
    return brightness / 255

def process_images(source_folder, target_folder, brightness_factor):
    """
    Process all images in the source folder, adjusting their brightness,
    and saving them to the target folder.
    """
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    for root, _, files in os.walk(source_folder):
        for file_name in files:
            if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
                source_path = os.path.join(root, file_name)
                relative_path = os.path.relpath(source_path, source_folder)
                target_path = os.path.join(target_folder, relative_path)

                target_dir = os.path.dirname(target_path)
                if not os.path.exists(target_dir):
                    os.makedirs(target_dir)

                adjust_brightness(source_path, target_path, brightness_factor)

                with Image.open(target_path) as image:
                    print(f"Processed {relative_path}, Brightness: {calculate_brightness(image)}")



# Example usage:
source_folder = r'F:\Dataset\sumdata(yes)\SumData\light-set\images\highlight-val'
target_folder = r'F:\Dataset\sumdata(yes)\SumData\light-set\images\h0.4-val'
brightness_factor = 0.40
# 1.2 means 20% brighter, 0.8 means 20% darkerc

process_images(source_folder, target_folder, brightness_factor)
